<template>
  <div>
    <el-tabs type="card" @tab-click="handleTabClick" v-model="activeTab" >
      <el-button @click="exportDialog = true">导出Excel</el-button>
      <el-tab-pane label="投资计算" name="investment">
        <el-container>
          <el-table :data="tableData"  stripe style="width: 100%" @selection-change="handleSelectionChange" ref="multipleTable">
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>
            <el-table-column prop="id" label="ID" align="center" sortable></el-table-column>
            <el-table-column prop="rent" label="房租(万/年)" align="center"></el-table-column>
            <el-table-column prop="amount" label="房间数量(间)" align="center"></el-table-column>
            <el-table-column prop="price" label="房价(元/间夜)" align="center"></el-table-column>
            <el-table-column prop="occupancyRate" label="出租率(%)" align="center"></el-table-column>
            <el-table-column prop="phone" label="号码" align="center"></el-table-column>
            <el-table-column prop="createTime" label="创建日期" align="center" sortable>
              <template slot-scope="scope">
                {{scope.row.createTime | moment("YYYY-MM-DD HH:mm:ss")}}
              </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="更改日期" align="center" sortable>
              <template slot-scope="scope">
                {{scope.row.updateTime | moment("YYYY-MM-DD HH:mm:ss")}}
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="180">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button
                  v-if="scope.row.isDelete === 0"
                  size="mini"
                  type="danger"
                  @click="handleAction(scope.row, 'comments', 'delete')">删除</el-button>
                <el-button
                  v-else
                  size="mini"
                  type="info"
                  @click="handleAction(scope.row, 'comments', 'restore')">恢复</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-container>
        <el-row>
          <el-pagination
            background
            layout="prev, pager, next"
            :total="investmentPage.total"
            :page-size="investmentPage.pageSize"
            :current-page="investmentPage.currentPage"
            @size-change="handlePageAction"
            @current-change="handlePageAction"
            @prev-text="handlePageAction"
            @next-text="handlePageAction">
          </el-pagination>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="留言管理" name="comments">
        <!--<el-button @click="exportDialog = true">导出Excel</el-button>-->
        <!--<el-button @click="toggleSelection()">取消选择</el-button>-->
        <el-container>
          <el-table :data="commentsData"  stripe style="width: 100%" tooltip-effect="dark" @selection-change="handleSelectionChange" ref="multipleTable" id="commentsTable">
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>
            <el-table-column prop="id" label="ID" align="center"></el-table-column>
            <!--<el-table-column prop="otherTypes" v-if="hideRow"></el-table-column>-->
            <el-table-column prop="types" label="咨询类型" align="center"  style="text-align: justify" width="180">
              <template slot-scope="scope">
                <span v-for="item in scope.row.types" :key="item.id">{{item}}
                  <!--<span v-if="index < scope.row.types.length-1">,</span>-->
                </span>
                <span v-if="scope.row.otherTypes !== null">{{scope.row.otherTypes}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="姓名" align="center"></el-table-column>
            <el-table-column prop="email" label="邮箱" align="center"></el-table-column>
            <el-table-column prop="city" label="城市" align="center"></el-table-column>
            <el-table-column prop="sex" label="性别" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.sex === 1">男</span>
                <span v-else>女</span>
              </template>
            </el-table-column>
            <el-table-column prop="property" label="是否有物业" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.property === 1">有</span>
                <span v-else>无</span>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建日期" align="center">
              <template slot-scope="scope">
                {{scope.row.createTime | moment("YYYY-MM-DD HH:mm:ss")}}
              </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="更改日期" align="center">
              <template slot-scope="scope">
                {{scope.row.updateTime | moment("YYYY-MM-DD HH:mm:ss")}}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" align="center">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button
                  v-if="scope.row.isDelete === 0"
                  size="mini"
                  type="danger"
                  @click="handleAction( scope.row, 'comments', 'delete')">删除</el-button>
                <el-button
                  v-else
                  size="mini"
                  type="info"
                  @click="handleAction(scope.row, 'comments', 'restore')">恢复</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-container>
        <el-row>
          <el-pagination
            background
            layout="prev, pager, next"
            :total="commentsPage.total"
            :page-size="commentsPage.pageSize"
            :current-page="commentsPage.currentPage"
            @size-change="handlePageAction"
            @current-change="handlePageAction"
            @prev-text="handlePageAction"
            @next-text="handlePageAction">
          </el-pagination>
        </el-row>
      </el-tab-pane>
    </el-tabs>
    <!--dialog part-->
    <el-dialog :visible.sync="exportDialog" title="请选择需要导出数据的开始时间和结束时间"  center>
      <div class="data-wrap">
        <el-row>
          <el-radio-group v-model="exportSelected">
            <el-radio label="investment">投资咨询</el-radio>
            <el-radio label="comments">客户留言</el-radio>
          </el-radio-group>
        </el-row>
        <el-date-picker
          v-model="startEndDate"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-dd"
          :picker-options="pickerOptions">
        </el-date-picker>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="exportDialog = false">取 消</el-button>
        <el-button type="primary" @click="exportExcelByDate">导 出</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Consumer',
  data () {
    return {
      activeTab: 'investment',
      startEndDate: '',
      exportDialog: false,
      exportSelected: 'investment',
      tableData: [],
      commentsData: [],
      commentsPage: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      },
      investmentPage: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      },
      userForm: {
        id: '',
        username: '',
        password: '',
        rePassword: '',
        email: '',
        phone: '',
        type: '',
        registrationInfo: '',
        createTime: '',
        updateTime: '',
        isDelete: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, message: '用户名用户名最少两个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 16, message: '密码长度为6-16位', trigger: 'blur' }
        ],
        rePassword: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { validator: this.validateRePassword, trigger: 'blur' }
        ],
        email: [
          { type: 'email', required: true, message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入正确的手机号码', trigger: 'blur' },
          {pattern: /^1[34578]\d{9}$/, message: '请输入长度为11位的手机号码'}
        ]
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  methods: {
    // 获取投资计算列表
    getInvestments: function (index, pageSize) {
      this.axios.get(getGServerUrl() + '/investment/find/pages', {
        params: {
          index: index,
          pageSize: pageSize
        }
      })
        .then(response => {
          let investments = response.data.data.investment
          this.tableData = investments.list
          this.investmentPage.total = investments.total
          console.log('investmentPage total:%d', this.investmentPage.total)
        })
    },
    // 获取留言列表
    getComments: function (currentIndex, pageSize) {
      this.axios.get(getGServerUrl() + '/comments/find/pages', {
        params: {
          index: currentIndex,
          pageSize: pageSize
        }
      })
        .then(response => {
          let comments = response.data.data.comments
          console.log(response)
          this.commentsData = comments.list
          this.commentsPage.total = comments.total
        })
    },
    // 处理网络请求
    handleAction: function (row, type, action) {
      let msgAction = ''
      let requestUrl = getGServerUrl()
      requestUrl = requestUrl + '/' + type + '/' + action + '/' + row.id
      this.axios.delete(requestUrl).then(response => {
        let count = response.data.data.count
        if (count > 0) {
          if (action === 'delete') {
            row.isDelete = 1
            msgAction = '删除'
          } else if (action === 'restore') {
            row.isDelete = 0
            msgAction = '恢复'
          }
          this.$message({
            message: msgAction + '成功：' + count,
            type: 'success'
          })
        }
      })
        .catch(error => {
          if (action === 'delete') {
            msgAction = '删除'
          } else if (action === 'restore') {
            msgAction = '恢复失败'
          }
          this.$message({
            message: msgAction + '失败: ' + error,
            type: 'error'
          })
        })
    },
    // 翻页处理
    handlePageAction: function (currentIndex) {
      console.log('current tab:%s current page:%s', this.activeTab, currentIndex)
      let currentTab = this.activeTab
      if (currentTab === 'investment') {
        this.getInvestments(currentIndex, this.investmentPage.pageSize)
      } else if (currentTab === 'comments') {
        this.getComments(currentIndex, this.commentsPage.pageSize)
      }
    },
    // tab点击事件
    handleTabClick (tab, event) {
      console.log('handleTabClick tab:', tab.name)
      this.exportSelected = tab.name
    },
    // 编辑
    handleEdit: function (index, row) {
      console.log(row)
      this.userForm = row
      this.activeTab = 'add'
    },
    // 提交表单
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = getGServerUrl()
          console.log(this.userForm.id)
          if (this.userForm.id === '') {
            url += '/user/add'
          } else {
            url += '/user/update'
          }
          this.axios.post(url, this.userForm)
            .then(response => {
              console.log(response)
              if (response.data.code === 200) {
                this.$message({
                  message: '新增成功:200',
                  type: 'success'
                })
                this.$refs[formName].resetFields()
                this.getInvestments(this.investmentPage.currentPage, this.investmentPage.pageSize)
                this.activeTab = 'update'
              }
            })
            .catch(error => {
              this.$message({
                message: '更新失败:' + error,
                type: 'error'
              })
            })
        } else {
          this.$message({
            message: '操作失败，请检查输入是否正确',
            type: 'error'
          })
        }
      })
    },
    validateRePassword (rule, value, callback) {
      if (value !== this.userForm.password) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    },
    toggleSelection (rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    exportExcelByTable: function (tableName) {
      // console.log(tableName)
      // let wb = XLXS.utils.table_to_book(document.getElementById(tableName))
      // XLXS.writeFile(wb, 'test.xlsx')
    },
    exportExcelByDate: function () {
      console.log(this.startEndDate)
      // this.httpAction(getGServerUrl() + '/' + this.exportSelected + '/find/between', 'get', {'startDate': this.startEndDate[0], 'endDate': this.startEndDate[1]},
      //   function (response) {
      //     console.log('on exportExeclDate: %o', response)
      //   })
      this.axios.get(getGServerUrl() + '/' + this.exportSelected + '/find/between', {
        params: {
          startDate: this.startEndDate[0],
          endDate: this.startEndDate[1]
        }
      })
        .then(response => {
          let data = response.data.data.comments
          if (data.length === 0) {
            this.$message({
              message: '改时间段未获取到任何数据',
              type: 'error'
            })
            return
          }
          if (this.exportSelected === 'comments') {
            // excel 表头
            const thMap = {'id': 'ID', 'types': '咨询类型', 'name': '姓名', 'email': '邮箱', 'city': '城市', 'sex': '性别', 'property': '是否有物业', 'createTime': '留言日期'}
            const keyArr = ['id', 'types', 'name', 'email', 'city', 'sex', 'property', 'createTime']
            // data.map(v => filterVal.map(k => v[k]))
            const [fileName, fileType, sheetName] = [this.startEndDate[0] + this.startEndDate[1] + '-留言', 'xlsx', '留言页面']
            const replaceMap = {'sex': {'0': '女', '1': '男'}, 'type': {'0': '还钱', '1': '借钱'}, 'property': {'0': '否', '1': '是'}}
            this.$toExcel({thMap, data, fileName, fileType, sheetName, keyArr, replaceMap})
            this.$notify.info({
              title: '消息',
              message: '开始导出',
              position: 'bottom-left'
            })
            this.exportDialog = false
          } else if (this.exportSelected === 'investment') {
            const thMap = {'id': 'ID', 'rent': '房租(万/年)', 'amount': '房间数量(间)', 'price': '房价(元/间夜)', 'occupancyRate': '出租率(%)', 'phone': '手机号码', 'createTime': '创建日期'}
            const keyArr = ['id', 'rent', 'amount', 'price', 'occupancyRate', 'phone', 'createTime']
            // const replaceMap = {'sex': {'0': '女', '1': '男'}, 'type': {'1': 'aaa'}, 'property': {'0': '没有', '1': '有'}}
            const [fileName, fileType, sheetName] = [this.startEndDate[0] + this.startEndDate[1] + '-投资计算', 'xlsx', '投资页面']
            this.$toExcel({thMap, data, fileName, fileType, sheetName, keyArr})
            this.$notify.info({
              title: '消息',
              message: '开始导出',
              position: 'bottom-left'
            })
            this.exportDialog = false
          }
        })
        .catch(error => {
          console.log(error)
        })
    }
  },
  mounted: function () {
    this.getInvestments(this.investmentPage.currentPage, this.investmentPage.pageSize)
    this.getComments(this.commentsPage.currentPage, this.commentsPage.pageSize)
  }
}
</script>

<style scoped>
  .registerForm{
    text-align: center;
  }
  .el-form{
    width: 400px;
    display: inline-block;
    border: solid 1px #bdc8d6;
    padding: 20px;
  }
.el-row{
  text-align: center;
  padding: 20px;
}
  .data-wrap{
    text-align: center;
  }
</style>
